#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json

from bottle import Bottle
from bottle import request, response

from excel.EGI.EgiDictUtil import EgiDictUtil

EgcAdm = Bottle()


@EgcAdm.hook('before_request')
def validate():
    REQUEST_METHOD = request.environ.get('REQUEST_METHOD')
    HTTP_ACCESS_CONTROL_REQUEST_METHOD = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
    if REQUEST_METHOD == 'OPTIONS' and HTTP_ACCESS_CONTROL_REQUEST_METHOD:
        request.environ['REQUEST_METHOD'] = HTTP_ACCESS_CONTROL_REQUEST_METHOD


@EgcAdm.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'  # 允许所有域名的请求
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, PUT, HEAD, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'origin,content-type,accept,authorization,x-requested-with'
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers['Access-Control-Max-Age'] = 86400
    response.status = 200


# Excel自研数据演算服务
# Vue+ele管理台界面数据接口

class EgcAdminRoute:
    TEST_YEAR = range(101)

    json_data_file = ""
    ERROR_CODE = {
        "80": "数据读取异常错误，请联系管理员",
        "99": "处理参数错误",
        "100": "数据添加失败，请检查服务端日志",
        "102": "数据更新失败，请检查服务端日志",
        "103": "数据删除失败，请检查服务端日志",
        "104": "数据停止失败，请检查服务端日志",
        "105": "数据恢复失败，请检查服务端日志",
        "106": "数据激活失败，请检查服务端日志",
        "109": "数据不存在，数据处理失败",
    }

    impl = None

    def __init__(self, service):
        EgcAdminRoute.impl = service
        return

    @staticmethod
    @EgcAdm.post('/initKeyParam')
    def init_cal_param():
        # select_payment = request.forms.
        if request.json is not None:
            select_anb = request.json['select_anb']  # 翌年歲
            annual_saving = request.json['annual_saving']  # 每年儲蓄金額
            saving_payment_term = request.json['saving_payment_term']  # 儲蓄供款期
            repeat_saving_plan = request.json['repeat_saving_plan']  # 重複儲蓄計劃
            repeat_saving_growth_rate = request.json['repeat_saving_growth_rate']  # 重複儲蓄增長率
            saving_sum_assured = request.json['saving_sum_assured']  # 儲蓄名義金額
            currency = request.json['currency']  # 貨幣
            surrender_anb = request.json['surrender_anb']  # 退保翌年歲
            withdrawal_starting_anb = request.json['withdrawal_starting_anb']  # 提款開始翌年歲
            fst_year_withdrawal = request.json['fst_year_withdrawal']  # 首年提款
            inflation = request.json['inflation']  # 通脹率
            withdrawal_years = request.json['withdrawal_years']  # 提取年期
            promotion = request.json['promotion']  # 推廣優惠
            lump_sum_prepaid = request.json['lump_sum_prepaid']  # 一筆過預繳
            extra_withdrawal = request.json['extra_withdrawal']  # 額外提取
            if select_anb == None:
                return {'code': EgcAdminRoute.ERROR_CODE["99"], 'data': None, 'message': '次年歲'}
            if not promotion is None:
                promotion = 'Y' if promotion else 'N'
            if not lump_sum_prepaid is None:
                lump_sum_prepaid = 'Y' if lump_sum_prepaid else 'N'
            str_res = EgiDictUtil.make_json_key(select_anb=select_anb, annual_saving=annual_saving,
                                                saving_payment_term=saving_payment_term,
                                                repeat_saving_plan=repeat_saving_plan,
                                                repeat_saving_growth_rate=repeat_saving_growth_rate,
                                                saving_sum_assured=saving_sum_assured, currency=currency,
                                                surrender_anb=surrender_anb,
                                                withdrawal_starting_anb=withdrawal_starting_anb,
                                                fst_year_withdrawal=fst_year_withdrawal, inflation=inflation,
                                                withdrawal_years=withdrawal_years, promotion=promotion,
                                                lump_sum_prepaid=lump_sum_prepaid, extra_withdrawal=extra_withdrawal, )
            str_res = "EGC-" + str_res
            hitnnt = EgcAdminRoute.impl.do_chck_key_exist(str_res)
            obj_data = None
            if hitnnt['code'] == 200:
                if hitnnt['data']:
                    obj_data = {"key": str_res, "hit": hitnnt, "res_msg": "中签"}
                else:
                    obj_data = {"key": str_res, "hit": hitnnt, "res_msg": "未中签"}
            else:
                return {'code': 99, 'data': obj_data, 'message': EgcAdminRoute.ERROR_CODE["99"]}
            return {'code': 200, 'data': obj_data, 'message': ""}

    @staticmethod
    @EgcAdm.get('/initStdBaseTab')
    def cal_purnm():
        strPram = request.params.strPram
        if strPram is None or len(strPram) == 0:
            return {'code': 99, 'data': None, 'message': EgcAdminRoute.ERROR_CODE["99"]},
        res = EgcAdminRoute.impl.do_std_base_tab(str_param=strPram, years=EgcAdminRoute.TEST_YEAR, withdrawals=[])
        if res["code"] != 200:
            return {'code': 99, 'data': None, 'message': EgcAdminRoute.ERROR_CODE["99"]}
        view_list = json.loads(res['data'])
        return {'code': 200, 'data': view_list, 'message': ""}

    @staticmethod
    @EgcAdm.post('/cal')
    def cal_purnm():
        if request.json is not None:
            strPram = request.json['strPram']
            withdrawals = request.json['withdrawals']
            res = EgcAdminRoute.impl.do_cal(str_param=strPram, years=EgcAdminRoute.TEST_YEAR,
                                            withdrawals=withdrawals)
            if res["code"] != 200:
                return {'code': 99, 'data': None, 'message': EgcAdminRoute.ERROR_CODE["99"]}
            view_list = json.loads(res['data'])
            # view_list = chg_Json2_list(arrays, LfreeObj.DATA_COLUMN)
            return {'code': 200, 'data': view_list, 'message': ""}
